package com.woniuxy.cloud.carl.carlgoods.app.apiImpl;

import cn.hutool.core.bean.BeanUtil;
import com.woniuxy.cloud.carl.carlgoods.client.PropValueClient;
import com.woniuxy.cloud.carl.carlgoods.client.dto.PropValueDto;
import com.woniuxy.cloud.carl.carlgoods.client.param.AddpropValueParam;
import com.woniuxy.cloud.carl.carlgoods.infra.mapper.PropValueMapper;
import com.woniuxy.cloud.carl.carlgoods.infra.mapper.SpuPropMapper;
import com.woniuxy.cloud.carl.carlgoods.infra.model.PropValue;
import com.woniuxy.cloud.carl.carlgoods.infra.model.SpuProp;
import com.woniuxy.result.Result;
import com.woniuxy.utils.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
@CrossOrigin("*")
public class PropValueImpl implements PropValueClient {
    @Resource
    private PropValueMapper propValueMapper;
    @Resource
    private SpuPropMapper spuPropMapper;
    @Override
    public Result addpropValue(AddpropValueParam param) {
        SpuProp spuProp = spuPropMapper.selectById(param.getPropId());
        Assert.state(spuProp!=null,"该种属性不存在，无法添加值");
        PropValue propValue = BeanUtil.toBean(param, PropValue.class);
        propValueMapper.insert(propValue);
        return Result.success();
    }

    @Override
    public Result<List<PropValueDto>> list() {
        List<PropValue> propValues = propValueMapper.selectList(null);
        List<PropValueDto> propValueDtos = BeanUtil.copyToList(propValues, PropValueDto.class);
        for (PropValueDto propValueDto : propValueDtos) {
            Long propId = propValueDto.getPropId();
            SpuProp spuProp = spuPropMapper.selectById(propId);
            propValueDto.setPropName(spuProp.getPropName());
        }

        return Result.success(propValueDtos);
    }
}
